package ru.home.documentmanager.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import ru.home.documentmanager.dao.DAO;

public abstract class AbstractDAO<T extends Serializable> implements DAO<T> {

    private final Class<T> type;

    @Autowired
    private SessionFactory sessionFactory;

    public AbstractDAO(Class<T> type) {
        this.type = type;
    }

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void save(T object) {
        getSession().save(object);
    }

    @Override
    public void update(T object) {
        getSession().update(object);
    }

    @Override
    public void saveOrUpdate(T object) {
        getSession().saveOrUpdate(object);
    }

    @Override
    public void delete(T object) {
        getSession().delete(object);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void delete(long id) {
        Session sess = getSession();
        T obj = (T) sess.load(type, id);
        getSession().delete(obj);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> find() {
        return getSession().createCriteria(type).list();
    }

    @SuppressWarnings("unchecked")
    @Override
    public T find(long id) {
        return (T) getSession().load(type, id);
    }

}
